import { login, getUserInfo } from '@/api'
import md5 from 'md5'
import { setItem, getItem, removeAllItem } from '@/utils/storage'
import { setTimeStamp } from '@/utils/auth'
import { TOKEN } from '@/constant'
import router from '@/router'
export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || '', // 先在localStorage中获取token，获取不到设置'',
    user: {}
  }),
  mutations: {
    setToken(state, token) {
      // 向vuex中设置token
      state.token = token
      // 向localStorage中存储token
      setItem(TOKEN, token)
    },
    setUserInfo(state, userInfo) {
      state.user = userInfo
      // setItem(USER, userInfo)
    }
  },
  actions: {
    login(context, userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({
          username,
          password: md5(password)
        }).then(res => {
          resolve(res)
          context.commit('setToken', res.token)
          // 保存时间
          setTimeStamp()
          router.push('/')
          // this.commit('user/setToken', res.data.data.token)
        }).catch(err => {
          reject(err)
        })
      })
    },
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          resolve(res)
          commit('setUserInfo', res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    logout({ commit }) {
      this.dispatch('permission/resetRoute')
      // 清理 vuex中的token和用户信息
      commit('setToken', '')
      commit('setUserInfo', {})
      // 清理本地中的所有缓存
      removeAllItem()
      // 清理所有的权限配置
      // TODO 清理权限配置
      router.push('/login')
    }
  }
}
